package org.wrigut.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import org.wrigut.scanlib.Scanner;
import org.wrigut.scanlib.Token;

/* Main.java
 * 
 * Project 1 - CS 3361
 * 
 * Authors: Chris Gutierrez
 *          Jordan Wright
 *          
 * This class implements the Parser application. It uses the scanlib to tokenize the input
 * from the specified file. Then, the string of tokens is parsed using the Parser class
 * to create a ParseTree object which represents the parse tree of the given input.
 * The TreeReader class transforms the tree into XML which is shown on screen.
 */

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length == 1) {
			parseFile(new File(args[0]));
		} else {
			System.out.println("Invalid arguments");
		}
	}
	
	private static void parseFile(File f) {
		BufferedReader reader;
		StringBuilder buffer = new StringBuilder();
		String nl = "\n";
		Scanner scanner;
		Parser parser;
		ParseTree output = null;
		//check the file
		if (!f.isFile()) {
			System.out.println("Not a file");
			return;
		}
		//initialize the file reader
		try {
			reader = new BufferedReader(new FileReader(f));
		} catch (FileNotFoundException e) {
			System.out.println("The file doesn't exist");
			return;
		}
		//read the file
		String line;
		try {
			line = reader.readLine();
		} catch (java.io.IOException ex) {
			System.out.println("Error reading file");
			return;
		}
		while (line != null) {
			buffer.append(line);
			buffer.append(nl);
			try {
				line = reader.readLine();
			} catch (IOException ex) {
				System.out.println("Error reading file");
				return;
			}
		}
		//the file has been read, scan it
		scanner = new Scanner(buffer.toString());
		ArrayList<Token> tokens = scanner.scanAll();
		if (tokens == null) {
			System.out.println("Scanning error");
			return;
		}
		//successful scan, try to parse
		try {
			parser = new Parser(tokens);
			output = parser.getRoot();
		} catch (ParseException e) {
			System.out.println("Parsing error: "+e.getMessage());
			return;
		}
		//show the output
		TreeReader tr = new TreeReader(output);
		line = null;
		while ((line = tr.getLine()) != null) {
			System.out.println(line);
		}
	}

}
